package cn.tang.tframe.common.base;

import cn.tang.tframe.common.utils.lang.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;


public class WebResult implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4290792342654695072L;
	private String status;
	private String message;
	private Object data;

	public WebResult() {
	}

	public WebResult(ResultCode status, Object data, String message) {
		this.status = status.getCode();
		this.data = data;
		this.message = message;
	}
	public WebResult(String status, Object data, String message) {
		this.status = status;
		this.data = data;
		this.message = message;
	}

	public boolean isSuccess() {
		return null != this.getStatus() && this.getStatus().equals(ResultCode.SUCCESS.getCode());
	}

	public static WebResult success() {
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("result", true);
		return new WebResult(ResultCode.SUCCESS, temp, "");
	}

	public static WebResult success(Object data) {
		if (data == null)
			return success();
		return new WebResult(ResultCode.SUCCESS, data, "");
	}

	public static WebResult successList(Object data) {
		Map<String, Object> results = new HashMap<>();
		results.put("results", data);
		return success(results);
	}

	public static WebResult sysFail(String message) {
		return new WebResult(ResultCode.OTHER, null, message);
	}

	public static WebResult noLogin() {
		return new WebResult(ResultCode.NOTLOGIN, null, ResultCode.NOTLOGIN.getDesc());
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public static WebResult fromBaseResult(BaseResult baseResult) {
		return fromBaseResult(baseResult, null);
	}

	public static WebResult fromBaseResult(BaseResult baseResult, String defaulErrorMsg) {
		if (StringUtils.isBlank(defaulErrorMsg)) {
			defaulErrorMsg = "系统繁忙，请稍后再试！";
		}
		if (null != baseResult) {
			if (baseResult.getSuccess()) {
				return success(baseResult.getModel());
			} else if (null != baseResult.getResultCode() && null != ResultCode.fromCode(baseResult.getResultCode())) {
				switch (ResultCode.fromCode(baseResult.getResultCode())) {
				case NOTLOGIN:
					return noLogin();
				case OTHER:
					return sysFail(StringUtils.isNotBlank(baseResult.getMessage()) ? baseResult.getMessage()
							: defaulErrorMsg);
				}
			}
		}
		return sysFail(defaulErrorMsg);
	}

	@Override
	public String toString() {
		return "WebResult{" + "status='" + status + '\'' + ", message='" + message + '\'' + ", data=" + data + '}';
	}
}
